package com.anywhere.freightman.car.controller;

import com.anywhere.freightman.car.model.CarModel;
import com.anywhere.freightman.car.service.ICarService;
import com.anywhere.freightman.client.CarLocationTestOpenClient;
import com.anywhere.freightman.common.ContextKeys;
import com.anywhere.freightman.common.annotation.Permission;
import com.anywhere.freightman.common.entity.ReturnResp;
import com.anywhere.freightman.common.entity.car.LocationEntity;
import com.anywhere.freightman.common.entity.car.TrackPoint;
import com.anywhere.freightman.common.entity.user.Account;
import com.anywhere.freightman.common.enumeration.RoleType;
import com.anywhere.freightman.common.ex.CustomException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("location")
@Api(tags = "车辆定位查询")
public class LocationController {

    @Autowired
    private CarLocationTestOpenClient carLocationTestOpenClient;
    @Autowired
    private ICarService carService;

    @GetMapping("{carNumber}")
    @ApiOperation("获取最后一次车辆定位")
    @Permission(code = "CAR")
    public ReturnResp getLastLocation(HttpServletRequest httpRequest,
                                      @PathVariable("carNumber") String carNumber) throws Exception {
        Account account = (Account) httpRequest.getAttribute(ContextKeys.REQUEST_ACCOUNT);
        CarModel carModel = carService.getByCarNumber(carNumber);
        if (carModel == null || (!account.getType().equals(RoleType.ADMIN) && !account.getCompanyId().equals(carModel.getCompanyId()))) {
            throw new CustomException("车辆信息不存在");
        }
        LocationEntity lastLocation = carLocationTestOpenClient.getLastLocation(carModel.getCarNumber());
        return ReturnResp.buildOk(lastLocation);
    }

    @GetMapping("track/{carNumber}")
    @ApiOperation("行车轨迹查询")
    @Permission(code = "CAR")
    public ReturnResp getTrackList(HttpServletRequest httpRequest,
                                   @PathVariable("carNumber") String carNumber,
                                   @RequestParam("startTime") Long startTime,
                                   @RequestParam("endTime") Long endTime) throws Exception {
        Account account = (Account) httpRequest.getAttribute(ContextKeys.REQUEST_ACCOUNT);
        CarModel carModel = carService.getByCarNumber(carNumber);
        if (carModel == null || (!account.getType().equals(RoleType.ADMIN) && !account.getCompanyId().equals(carModel.getCompanyId()))) {
            throw new CustomException("车辆信息不存在!");
        }
        List<TrackPoint> trackPoints = carLocationTestOpenClient.getTrack(carNumber, startTime, endTime);
        return ReturnResp.buildOk(trackPoints);
    }
}
